# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
from scrapy.http import HtmlResponse
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# 初始化browser
# options = Options()
# options.add_experimental_option('excludeSwitches', ['enable-automation'])
# # options.add_argument('--headless')
# browser = webdriver.Chrome(options=options)
# browser.get('https://www.zhipin.com/?ka=header-home')


class SlaveRequestsSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class SlaveRequestsDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class PositionDetailMiddleware(object):

    options = Options()
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    # options.add_argument('--headless')
    browser = webdriver.Chrome(options=options)
    browser.get('https://www.zhipin.com/?ka=header-home')

    # def __init__(self):
    #     self.options = Options()
    #     self.options.add_experimental_option('excludeSwitches', ['enable-automation'])
    #     self.options.add_argument('--headless')
    #     self.browser = webdriver.Chrome(options=self.options)
    #     self.browser.get('https://www.zhipin.com/?ka=header-home')

    def process_request(self, request, spider):
        self.browser.get(request.url)
        html = self.browser.page_source
        return HtmlResponse(
            url=request.url,
            body=html,
            encoding='utf-8'
        )
        # 设置cookie
        # request.cookies = {
        #     '__c': '1565423503',
        #     '__g': '-',
        #     '__l': 'l=%2Fwww.zhipin.com%2Fweb%2Fcommon%2Fsecurity-check.html%3Fseed%3DmCWRHqmbePZUBsTq08IOBlagUFeO'
        #            'Fx0QdEGIyzXxXZ0%253D%26name%3D0d4a1b14%26ts%3D1565423502435%26callbackUrl%3D%252Fjob_'
        #            'detail%252Fdbce69de2f96ae8b0nV72tm8FFA%257E.html&r=',
        #     # 'lastCity': '101010100',
        #     'Hm_lvt_194df3105ad7148dcf2b98a91b5e727a': '1565316888,1565368583',
        #     '__a': '4688554.1565423503..1565423503.6.1.6.6',
        #     '__zp_stoken__': '44fcIr0YGxzPXpUDdswdcA2B8a03pRhiizQjqVmUQXLWixpXSpQldMmOLaz37B8r'
        #                      'JmlU6aUZDZh0vI9q5ge8ytu6iw%3D%3D',
        #
        #     'Hm_lpvt_194df3105ad7148dcf2b98a91b5e727a': '1565424303',
        # }

    # def process_response(self, request, response, spider):
    #     return response

    # def process_exception(self, request, exception, spider):
    #     # 遇到异常，更换IP
    #     print('异常')
    #     return request